const { Table } = require('voici.js');
const logger = require('../utils/logger');
const externalApi = require('./externalApi');
const database = require('../config/database');

class InternalService {
  constructor() {
    this.services = new Map();
    this.initServices();
  }

  /**
   * 初始化内部服务
   */
  initServices() {
    // 股票数据服务
    this.services.set('stock', {
      name: '股票数据服务',
      status: 'active',
      version: '1.0.0',
      endpoints: ['/data', '/analysis', '/prediction']
    });

    // 用户管理服务
    this.services.set('user', {
      name: '用户管理服务',
      status: 'active',
      version: '1.0.0',
      endpoints: ['/profile', '/preferences', '/history']
    });

    // 数据分析服务
    this.services.set('analytics', {
      name: '数据分析服务',
      status: 'active',
      version: '1.0.0',
      endpoints: ['/trends', '/patterns', '/insights']
    });

    logger.info('------服务初始化完成------');
  }

  /**
   * 获取服务状态
   * @param {string} serviceName - 服务名称
   * @returns {object} 服务状态信息
   */
  getServiceStatus(serviceName) {
    const service = this.services.get(serviceName);
    if (!service) {
      throw new Error(`服务不存在: ${serviceName}`);
    }
    
    return {
      ...service,
      timestamp: new Date().toISOString(),
      uptime: process.uptime()
    };
  }

  /**
   * 获取所有服务状态
   * @returns {Array} 所有服务状态
   */
  getAllServicesStatus() {
    const services = [];
    for (const [key, service] of this.services) {
      services.push({
        id: key,
        ...service,
        timestamp: new Date().toISOString(),
        uptime: process.uptime()
      });
    }
    return services;
  }

  /**
   * 执行内部任务
   * @param {string} taskType - 任务类型
   * @param {object} params - 任务参数
   * @returns {Promise} 任务执行结果
   */
  async executeTask(taskType, params = {}) {
    try {
      logger.info(`开始执行内部任务: ${taskType}`, { 
        cycleTime: params.cycleTime || '当前时间' 
      });
      
      let result;
      switch (taskType) {
        case 'dataSync':
          result = await this.syncData(params);
          break;
        default:
          throw new Error(`未知的任务类型: ${taskType}`);
      }
      
      // logger.info(`内部任务执行完成: ${taskType}`, { result });
      return result;
    } catch (error) {
      logger.error(`内部任务执行失败: ${taskType}`, { error: error.message });
      throw error;
    }
  }

  /**
   * 数据同步任务
   * @param {object} params - 同步参数
   * @returns {Promise} 同步结果
   */
  async syncData(params = {}) {
    // 获取周期时间，如果没有传入则使用当前时间
    const cycleTime = params.cycleTime || new Date().toLocaleString('zh-CN', {
      timeZone: 'Asia/Shanghai',
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-');
    const payload = {
      "appId": "appId01",
      "globalId": "786e4c21-70dc-435a-93bb-38",
      "marketType": "",
      "pageNo": 1,
      "pageSize": 50
    }
    const res = await externalApi.post(`https://emappdata.eastmoney.com/stockrank/getAllCurrentList`, payload);

    const rankList = res.data.map(item => {
      const { sc } = item;
      return `${sc.startsWith('SZ') ? '0.' : '1.'}${sc.substr(-6)}`
    })
    // console.log(rankList);

    const queryParams = {
      ut: 'f057cbcbce2a86e2866ab8877db1d059',
      fltt: 2,
      invt: 2,
      fields: 'f14,f148,f3,f12,f2,f13,f29',
      secids: rankList.join(',')
    }
    const res2 = await externalApi.get(`https://push2.eastmoney.com/api/qt/ulist.np/get`, { params: queryParams });
    // console.log(res2.data.diff);

    const fList = res2.data.diff.map((item, index) => {
      const { f2, f3, f12, f14 } = item;
      return {
        rank_num: index + 1,
        code: f12,
        name: f14,
        increase: f3,
        price_shot: f2,
        cycle_time: cycleTime // 使用定时任务的执行时间
      }
    })

    // 打印数据到控制台
    const config = {
      align: 'LEFT',
      border: { horizontal: '-', vertical: '|' },
      header: {
        // width: 10,
        bgColor: '#6184D8',
        textColor: '#d8b561'
      }
    };
    const table = new Table(fList.map(item => ({
      code: item.code,
      name: item.name,
      increase: item.increase,
      priceShot: item.price_shot,
      cycleTime: item.cycle_time
    })), config);
    table.print();
    
    // 将数据保存到MySQL数据库
    try {
      const result = await database.insertOrUpdate(
        'rank_every_day',
        fList,
        ['rank_num', 'code', 'name', 'increase', 'price_shot', 'cycle_time']
      );
      
      logger.info('股票数据已保存到数据库', {
        records: result.records,
        affectedRows: result.affectedRows
      });

      return {
        success: true,
        message: '数据同步完成',
        syncedItems: fList.length,
        dbAffectedRows: result.affectedRows,
        timestamp: new Date().toISOString()
      };
    } catch (dbError) {
      logger.error('数据保存到数据库失败', { error: dbError.message });
      // 即使数据库保存失败，也返回部分成功的结果
      return {
        success: false,
        message: '数据同步完成，但保存到数据库失败',
        syncedItems: fList.length,
        error: dbError.message,
        timestamp: new Date().toISOString()
      };
    }
  }

  /**
   * 获取系统统计信息
   * @returns {object} 系统统计
   */
  getSystemStats() {
    const stats = {
      uptime: process.uptime(),
      memory: process.memoryUsage(),
      cpu: process.cpuUsage(),
      services: this.services.size,
      timestamp: new Date().toISOString()
    };

    return stats;
  }
}

module.exports = new InternalService();
